# admin.py
from django.contrib import admin
from .models import ChanpinLeibie, Chanpin_gys, Chanpin, Dingdan


@admin.register(ChanpinLeibie)
class ChanpinLeibieAdmin(admin.ModelAdmin):
    list_display = ('name', 'description')
    search_fields = ('name',)
    ordering = ('name',)


@admin.register(Chanpin_gys)
class Chanpin_gysAdmin(admin.ModelAdmin):
    list_display = ('name', 'lxr', 'tel', 'dizhi')
    search_fields = ('name', 'tel')
    ordering = ('name',)


@admin.register(Chanpin)
class ChanpinAdmin(admin.ModelAdmin):
    list_display = ('title', 'jiage', 'jiage_dijia', 'leibie', 'gys')
    list_filter = ('leibie', 'gys')
    search_fields = ('title', 'gys')
    ordering = ('title',)  # 确保这里的字段名正确


import random
from datetime import datetime


def generate_ddh():
    date_part = datetime.now().strftime('%Y%m%d')
    random_part = '{:05d}'.format(random.randint(0, 99999))
    return f"{date_part}{random_part}"




@admin.register(Dingdan)
class dingdanAdmin(admin.ModelAdmin):
    list_display = ('ddh', 'ddtime', 'user_first_name', 'ddchanpin_titles', 'kehu')
    list_filter = ('ddh', 'ddtime', 'dduser__username')
    list_display_links = ('kehu', 'ddh', 'user_first_name')
    search_fields = ('ddh', 'ddtime', 'dduser')
    readonly_fields = ('ddh',)

    def user_first_name(self, obj):
        return obj.dduser.last_name

    user_first_name.short_description = '订单归属'

    def save_model(self, request, obj, form, change):
        if not obj.ddh:
            obj.ddh = generate_ddh()  # 确保你有这个函数定义
        super().save_model(request, obj, form, change)

    Dingdan.dduser.search_help_text = "sdas"

    def ddchanpin_titles(self, obj):
        return ', '.join(chanpin.title for chanpin in obj.ddchanpin.all())

    ddchanpin_titles.short_description = '订单产品名称'
